import React, { useState, useEffect, Suspense } from 'react'
import { Link, Route } from 'react-router-dom'
import { Breadcrumb, Tabs, Input, Select, DatePicker, Space, Button, Row, Col, Table, Modal } from "antd"
import { SearchOutlined, CloudUploadOutlined } from '@ant-design/icons';
import locale from 'antd/es/date-picker/locale/zh_CN';
import { useSelector, useDispatch } from 'react-redux'
import { PreLoanMangeAsyncAction, EditIdAction } from '../../store/preLoanStore/action'
import { GetInfoDetailApi } from '../../http/preLoanApi'
import { StateType } from './StateType';
// import List from '../PreLoanFirst/List'
import './index.scss'
import style from './index.module.scss'

const { TabPane } = Tabs;
const { Option } = Select
const { RangePicker } = DatePicker;
export default function FirstCheck() {
    //分页
    const [pageAndSize, setPageAndSize] = useState({
        currentPage: 1,
        pageSize: 10
    })
    const dispatch = useDispatch()
    const preLoanMange = useSelector((state) => state.preLoanMange)
    console.log('在初审页面获取数据', preLoanMange)
    const [data, setData] = useState([])
    const [dataDetail, setDataDetail] = useState([])

    //搜索字段
    const [name, setName] = useState('')
    const [phoneNumber, setPhoneNumber] = useState('')
    const [type, setType] = useState('')
    const [startDate, setStartDate] = useState('')
    const [endDate, setEndDate] = useState('')
    const [loanState, setLoanState] = useState([0, 4])

    // 从store中获得id
    const getId = (record) => {
        console.log('record', record.loan_id);
        const id = record.loan_id
        console.log(id);
        dispatch(EditIdAction(id))
    }

    // 在初审界面发起请求
    useEffect(() => {
        setData([])
        dispatch(PreLoanMangeAsyncAction({
            ...pageAndSize,
            data: {
                customer_name: name,
                customer_phone: phoneNumber,
                loan_type: type,
                application_startDate: startDate,
                application_endDate: endDate,
                loan_state: loanState
            }
        }))
    }, [pageAndSize, loanState])

    useEffect(() => {
        setData([])
        // console.log('preLoanMange', preLoanMange);
        if (preLoanMange.length) {
            // console.log('1111');
            // 渲染数据
            let arr = Array.prototype.slice.call(preLoanMange)
            console.log('arr', arr);
            const array = []
            let key = 0
            arr.forEach((item) => {
                let obj = {
                    key: key++,
                    loan_id: item.loan_id,
                    name: item.customer.name,
                    application_date: item.application_date,
                    phone: item.customer.phone,
                    applied_amount: item.applied_amount,
                    reimbursement_means: item.reimbursement_means,
                    time_limit: item.time_limit,
                    loan_type: item.loan_type,
                    state: StateType(item.state)
                };
                if (item.auditList.length > 0) {
                    const a = item.auditList.filter(item =>
                        item.state === "初审"
                    )
                    console.log(a);
                    obj.audit_time = a[0].audit_time.substr(0, 10)
                    obj.user_name = a[0].user.user_name
                }
                array.push(obj)
            })
            setData(array)
            console.log(array)
        }

    }, [preLoanMange])

    const columns = [
        {
            title: '借款编号',
            dataIndex: 'loan_id',
        },
        {
            title: '姓名',
            dataIndex: 'name',
        },
        {
            title: '申请日期',
            dataIndex: 'application_date',
        },
        {
            title: '手机号',
            dataIndex: 'phone',
        },
        {
            title: '申请额度',
            dataIndex: 'applied_amount',
        },
        {
            title: '还款方式',
            dataIndex: 'reimbursement_means',
        },
        {
            title: '借款期限',
            dataIndex: 'time_limit',
        },
        {
            title: '贷款类型',
            dataIndex: 'loan_type',
        },
        {
            title: '状态',
            dataIndex: 'state',
            render: (text, record) => (
                <>{record.state}{record.state === '复审驳回' || record.state === '初审拒绝' ? <Route> <Link onClick={() => showModal(record.loan_id)}>审核详情</Link></Route> : null}</>
                // {record.state === '复审驳回' ? record.state + <Route> <Link to='/' onClick={showModal}>审核详情</Link></Route > : record.state}
            )
        },
        {
            title: '初审时间',
            dataIndex: 'audit_time',
        },
        {
            title: '初审人员',
            dataIndex: 'user_name',
            render: (text, record) => (
                <>{record.user_name}{record.state === '初审通过' ? <Route>
                    <Link onClick={() => showModal(record.loan_id)}>审核详情</Link>
                </Route> : null}</>
                // {record.state === '复审驳回' ? record.state + <Route> <Link to='/' onClick={showModal}>审核详情</Link></Route > : record.state}
            )
        },
        {
            title: '操作',
            dataIndex: 'action',
            render: (text, record, index) =>
                // <Link to={{ pathname: '/home/preloan/preloandetail', search: "?loanId=" + loanId }} >查看</Link>
                <Link to='/home/detailInfo' onClick={() => { getId(record) }}>查看</Link>
        },
    ];

    // 模态框表格
    const columns1 = [
        {
            title: '审核时间',
            dataIndex: 'audit_time',
        },
        {
            title: '状态',
            dataIndex: 'state',
        },
        {
            title: "审核人员",
            dataIndex: 'user_name'
        },
        {
            title: "审核结果",
            dataIndex: 'audit_result'
        },
        {
            title: '反馈详情',
            dataIndex: "feedback"
        }
    ]


    //tab切换
    const callback = (key) => {
        if (key === '1') {
            setLoanState([0, 4])
            setPageAndSize({
                currentPage: 1,
                pageSize: 10
            })
        } else if (key === '2') {
            setLoanState([1])
            setPageAndSize({
                currentPage: 1,
                pageSize: 10
            })
        } else if (key === '3') {
            setLoanState([6])
            setPageAndSize({
                currentPage: 1,
                pageSize: 10
            })
        }
    }

    //获取分页
    const getPage = (page, pageSize) => {
        console.log(page, pageSize)
        setPageAndSize({
            currentPage: page,
            pageSize
        })
    }

    //搜索
    const onChangetype = (value) => {
        setType(value)
    }
    const onChangetime1 = (date, dateString) => {
        console.log('日期获取', date, dateString);
        setStartDate(dateString[0] + " 00:00:00")
        setEndDate(dateString[1] + " 23:59:59")
    }
    const onChangeName = (e) => {
        setName(e.target.value)
    }
    const onChangePhone = (e) => {
        setPhoneNumber(e.target.value)
    }
    const search = () => {
        dispatch(PreLoanMangeAsyncAction({
            ...pageAndSize,
            data: {
                customer_name: name,
                customer_phone: phoneNumber,
                loan_type: type,
                application_startDate: startDate,
                application_endDate: endDate,
                loan_state: loanState
            }
        }))
        setType('')
        setStartDate('')
        setEndDate('')
        setName('')
        setPhoneNumber('')
    }


    //模态框
    const [isModalVisible, setIsModalVisible] = useState(false);

    const showModal = (id) => {
        setIsModalVisible(true);

        GetInfoDetailApi(id).then((res) => {
            if (res.data.code === 200) {
                console.log('获取审核详情请求成功', res.data.data);
                let dataArr = res.data.data
                if (dataArr.length) {
                    let arr = Array.prototype.slice.call(dataArr)
                    console.log('审核详情数组', arr);
                    const array = []
                    let key = 0
                    arr.forEach((item) => {
                        let obj = {
                            key: key++,
                            audit_time: item.audit_time.substr(0, 10),
                            state: item.state,
                            user_name: item.user.user_name,
                            audit_result: item.audit_result,
                            feedback: item.feedback,
                        }
                        array.push(obj)

                    })
                    setDataDetail(array)
                    console.log('放进useState的数组', array)
                }
            }

        })
            .catch((err) => {
                console.log('获取审核详情请求失败', err);
            })
    };

    const handleOk = () => {
        setIsModalVisible(false);
    };

    const handleCancel = () => {
        setIsModalVisible(false);
    };
    return (
        <div className={style.box}>
            <Modal title="审核详情" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel} centered keyboard mask maskClosable>

                <Table columns={columns1} dataSource={dataDetail}
                    pagination={{
                        defaultPageSize: 5,
                        total: preLoanMange.count,
                        showTotal: total => `共${Math.ceil(total / pageAndSize.pageSize)}页/ ${total} 条数据`,
                        onChange: getPage
                    }}
                />
            </Modal>
            <Breadcrumb style={{ margin: '16px 0', display: "flex", justifyContent: "start" }}>
                <Breadcrumb.Item>首页</Breadcrumb.Item>
                <Breadcrumb.Item>贷前管理</Breadcrumb.Item>
                <Breadcrumb.Item>准入授信管理</Breadcrumb.Item>
            </Breadcrumb>
            <Tabs defaultActiveKey="1" onChange={callback} className='tabs'>
                <TabPane tab="待初审" key="1">
                    <div>
                        <Row gutter={{ xs: 8, sm: 16, md: 24, lg: 32 }}>
                            <Col className="gutter-row" span={6}>
                                <div>
                                    <Input placeholder="姓名" onChange={onChangeName} allowClear />
                                </div>
                            </Col>
                            <Col className="gutter-row" span={6}>
                                <div>
                                    <Input placeholder="手机号" onChange={onChangePhone} allowClear />
                                </div>
                            </Col>
                            <Col className="gutter-row" span={2}>
                                <div>
                                    <Select
                                        allowClear
                                        placeholder="贷款类型"
                                        optionFilterProp="children"
                                        onChange={onChangetype}
                                        filterOption={(input, option) =>
                                            option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                    >
                                        <Option value="个人信用">个人信用</Option>
                                    </Select>
                                </div>
                            </Col>
                            <Col className="gutter-row" span={6}>
                                <div>
                                    <Space direction="vertical" size={12}>
                                        <RangePicker locale={locale} onChange={onChangetime1} />
                                    </Space>
                                </div>
                            </Col>
                            <Col className="gutter-row" span={4}>
                                <div>
                                    <Button icon={<SearchOutlined />} type='button' onClick={search}>
                                        查询
                                    </Button>
                                </div>
                            </Col>
                        </Row>
                        <div className={style.pre_title}>
                            <p >数据列表</p>
                            <Button className='button'><CloudUploadOutlined className="icon" />导出</Button>
                        </div>
                        <Table columns={columns} dataSource={data} pagination={{
                            total: preLoanMange.length,
                            showQuickJumper: true,
                            showSizeChanger: true,
                            pageSizeOptions: ['1', '0', '30'],
                            showTotal: total => `共${Math.ceil(total / pageAndSize.pageSize)}页/ ${total} 条数据`,
                            onChange: getPage
                        }}
                        />
                    </div>

                </TabPane>
                <TabPane tab="已通过" key="2">

                    <div>
                        <Row gutter={{ xs: 8, sm: 16, md: 24, lg: 32 }}>
                            <Col className="gutter-row" span={6}>
                                <div>
                                    <Input placeholder="姓名" onChange={onChangeName} allowClear />
                                </div>
                            </Col>
                            <Col className="gutter-row" span={6}>
                                <div>
                                    <Input placeholder="手机号" onChange={onChangePhone} allowClear />
                                </div>
                            </Col>
                            <Col className="gutter-row" span={2}>
                                <div>
                                    <Select
                                        allowClear
                                        placeholder="贷款类型"
                                        optionFilterProp="children"
                                        onChange={onChangetype}
                                        filterOption={(input, option) =>
                                            option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                    >
                                        <Option value="个人信用">个人信用</Option>
                                    </Select>
                                </div>
                            </Col>
                            <Col className="gutter-row" span={6}>
                                <div>
                                    <Space direction="vertical" size={12}>
                                        <RangePicker locale={locale} onChange={onChangetime1} />
                                    </Space>
                                </div>
                            </Col>
                            <Col className="gutter-row" span={4}>
                                <div>
                                    <Button icon={<SearchOutlined />} type='button' >
                                        查询
                                    </Button>
                                </div>
                            </Col>
                        </Row>
                        <div className={style.pre_title}>
                            <p>数据列表</p>
                            <Button><CloudUploadOutlined className="icon" />导出</Button>
                        </div>
                        <Table columns={columns} dataSource={data} pagination={{
                            total: preLoanMange.length,
                            showQuickJumper: true,
                            showSizeChanger: true,
                            pageSizeOptions: ['10', '20', '30'],
                            showTotal: total => `共${Math.ceil(total / pageAndSize.pageSize)}页/ ${total} 条数据`,
                            onChange: getPage
                        }}
                        />
                    </div>
                </TabPane>
                <TabPane tab="已终止" key="3">

                    <div>
                        <Row gutter={{ xs: 8, sm: 16, md: 24, lg: 32 }}>
                            <Col className="gutter-row" span={6}>
                                <div>
                                    <Input placeholder="姓名" onChange={onChangeName} allowClear />
                                </div>
                            </Col>
                            <Col className="gutter-row" span={6}>
                                <div>
                                    <Input placeholder="手机号" onChange={onChangePhone} allowClear />
                                </div>
                            </Col>
                            <Col className="gutter-row" span={2}>
                                <div>
                                    <Select
                                        allowClear
                                        placeholder="贷款类型"
                                        optionFilterProp="children"
                                        onChange={onChangetype}
                                        filterOption={(input, option) =>
                                            option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                    >
                                        <Option value="个人信用">个人信用</Option>
                                    </Select>
                                </div>
                            </Col>
                            <Col className="gutter-row" span={6}>
                                <div>
                                    <Space direction="vertical" size={12}>
                                        <RangePicker locale={locale} onChange={onChangetime1} />
                                    </Space>
                                </div>
                            </Col>
                            <Col className="gutter-row" span={4}>
                                <div>
                                    <Button icon={<SearchOutlined />} type='button' >
                                        查询
                                    </Button>
                                </div>
                            </Col>
                        </Row>
                        <div className={style.pre_title}>
                            <p >数据列表</p>
                            <Button ><CloudUploadOutlined className="icon" />导出</Button>
                        </div>
                        <Table columns={columns} dataSource={data} pagination={{
                            total: preLoanMange.length,
                            showQuickJumper: true,
                            showSizeChanger: true,
                            pageSizeOptions: ['10', '20', '30'],
                            showTotal: total => `共${Math.ceil(total / pageAndSize.pageSize)}页/ ${total} 条数据`,
                            onChange: getPage
                        }}
                        />
                    </div>
                </TabPane>
            </Tabs>
        </div>
    )
}
